<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户ID" prop="userId">
        <el-input
          v-model="queryParams.userId"
          placeholder="请输入用户ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--<el-form-item label="审批人ID" prop="approverId">
        <el-input
          v-model="queryParams.approverId"
          placeholder="请输入审批人ID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <!--<el-form-item label="请假开始日期" prop="startDate">
        <el-date-picker clearable
          v-model="queryParams.startDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择请假开始日期">
        </el-date-picker>
      </el-form-item>-->
      <!--<el-form-item label="请假结束日期" prop="endDate">
        <el-date-picker clearable
          v-model="queryParams.endDate"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择请假结束日期">
        </el-date-picker>
      </el-form-item>-->
      <!--<el-form-item label="请假天数" prop="leaveDays">
        <el-input
          v-model="queryParams.leaveDays"
          placeholder="请输入请假天数"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <!--<el-form-item label="审批时间" prop="approvalTime">
        <el-date-picker clearable
          v-model="queryParams.approvalTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择审批时间">
        </el-date-picker>
      </el-form-item>-->
      <!--<el-form-item label="申请时间" prop="createdTime">
        <el-date-picker clearable
          v-model="queryParams.createdTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择申请时间">
        </el-date-picker>
      </el-form-item>-->
      <!--<el-form-item label="更新时间" prop="updatedTime">
        <el-date-picker clearable
          v-model="queryParams.updatedTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择更新时间">
        </el-date-picker>
      </el-form-item>-->
      <!--<el-form-item label="审批原因" prop="result">
        <el-input
          v-model="queryParams.result"
          placeholder="请输入审批原因"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <!--<el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:leave:add']"
        >新增</el-button>
      </el-col>-->
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:leave:edit']"
        >修改</el-button>
      </el-col>-->
     <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:leave:remove']"
        >删除</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:leave:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="leaveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="id"   v-if="false"/>
      <el-table-column label="用户姓名" align="center" prop="userName" />
      <!--<el-table-column label="审批人ID" align="center" prop="approverId"  />-->
      <el-table-column label="请假类型" align="center">
        <template slot-scope="{ row }">
          <!-- 使用对象映射实现类型转换 -->
          <span>{{
      {
        'ANNUAL': '年假',
        'SICK': '病假',
        'PERSONAL': '事假',
        'OTHER': '其他'
      }[row.leaveType] || '未知类型'
    }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假开始日期" align="center" prop="startDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假结束日期" align="center" prop="endDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="请假天数" align="center" prop="leaveDays" v-if="false" />
      <el-table-column label="请假原因" align="center" prop="reason"  v-if="false"/>
      <el-table-column label="审批状态" align="center">
        <template #default="{ row }">
          <el-button
            class="uniform-btn"
            :class="{
        'pending-btn': row.status === 'PENDING',
        'approve-btn': row.status === 'APPROVED',
        'reject-btn': row.status === 'REJECTED'
      }"
            :type="{
        'PENDING': 'warning',
        'APPROVED': 'success',
        'REJECTED': 'info'
      }[row.status]"
            @click="showResult(row)"
          >
            <!-- 新增状态映射：将英文状态转为中文 -->
            {{
            {
            APPROVED: '已通过',
            PENDING: '审批中',
            REJECTED: '已拒绝'
            }[row.status]
            }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="审批时间" align="center" prop="approvalTime" width="180" v-if="false">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.approvalTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" align="center" prop="createdTime" width="180" v-if="false">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createdTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" prop="updatedTime" width="180" v-if="false">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批原因" align="center" prop="result"  v-if="false"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:leave:edit']"
          >审批</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:leave:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改请假审批对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户ID" prop="userId">
          <el-input v-model="form.userId" disabled />
        </el-form-item>
        <el-form-item label="审批人ID" prop="approverId" v-if="false">
          <el-input v-model="form.approverId" placeholder="请输入审批人ID" />
        </el-form-item>
        <el-form-item label="请假开始日期" prop="startDate">
          <el-date-picker clearable
            v-model="form.startDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择请假开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="请假结束日期" prop="endDate">
          <el-date-picker clearable
            v-model="form.endDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择请假结束日期">
          </el-date-picker>
        </el-form-item>
        <!--<el-form-item label="请假天数" prop="leaveDays">
          <el-input v-model="form.leaveDays" disabled />
        </el-form-item>-->
        <el-form-item label="请假原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="审批时间" prop="approvalTime">
          <el-date-picker
            v-model="form.approvalTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择审批时间"
            :disabled="true"
          clearable>
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择审批状态" clearable>
            <el-option
              label="审批中"
              value="PENDING"
            />
            <el-option
              label="通过"
              value="APPROVED"
            />
            <el-option
              label="拒绝"
              value="REJECTED"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="createdTime" v-if="false">
          <el-date-picker clearable
            v-model="form.createdTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择申请时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新时间" prop="updatedTime" v-if="false">
          <el-date-picker clearable
            v-model="form.updatedTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="审批原因" prop="result">
          <el-input v-model="form.result" placeholder="请输入审批原因" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listLeave, getLeave, delLeave, addLeave, updateLeave } from "@/api/system/leave";

export default {
  name: "Leave",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 请假审批表格数据
      leaveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        approverId: null,
        leaveType: null,
        startDate: null,
        endDate: null,
        /*leaveDays: null,*/
        reason: null,
        status: null,
        approvalTime: this.formatDate(new Date()), // 设置为当前日期
        createdTime: null,
        updatedTime: null,
        result: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "用户ID不能为空", trigger: "blur" }
        ],
        leaveType: [
          { required: true, message: "请假类型不能为空", trigger: "change" }
        ],
        startDate: [
          { required: true, message: "请假开始日期不能为空", trigger: "blur" }
        ],
        endDate: [
          { required: true, message: "请假结束日期不能为空", trigger: "blur" }
        ],
        reason: [
          { required: true, message: "请假原因不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.userId = this.$store.state.user.id;
    this.getList();
  },
  methods: {
    formatDate(date) {
      const d = new Date(date);
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      return `${d.getFullYear()}-${month}-${day}`;
    },
    /** 查询请假审批列表 */
    getList() {
      this.loading = true;
      listLeave(this.queryParams).then(response => {
        this.leaveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        approverId: null,
        leaveType: null,
        startDate: null,
        endDate: null,
        /*leaveDays: null,*/
        reason: null,
        status: null,
        approvalTime: new Date().toISOString().split('T')[0], // 默认当前日期
        createdTime: null,
        updatedTime: null,
        result: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLeave(id).then(response => {
        this.form = response.data;
      // 强制设置审批时间为当前时间
      this.form.approvalTime = this.formatDate(new Date());
      this.open = true;
      this.title = "审批处理";
    });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getLeave(id).then(response => {
        this.form = response.data;
      this.form.approvalTime = this.formatDate(new Date()); // 强制设置当前时间
      this.open = true;
      this.title = "审批处理";
    });
    },
    // 提交表单时保留审批时间
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 确保传递审批时间
          this.form.approvalTime = this.formatDate(new Date());
          if (this.form.id != null) {
            updateLeave(this.form).then(response => {
              this.$modal.msgSuccess("审批成功");
            this.open = false;       // 关闭弹窗
            this.getList();          // 刷新列表
          }).catch(error => {
              this.$modal.msgError("审批失败：" + (error.message || "未知错误"));
          });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除请假审批编号为"' + ids + '"的数据项？').then(function() {
        return delLeave(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/leave/export', {
        ...this.queryParams
      }, `leave_${new Date().getTime()}.xlsx`)
    },
    showResult(row) {
      this.$alert(row.result || '暂无审批说明', '审批原因', {
        confirmButtonText: '确定'
      });
    },
  }
};
</script>
